﻿using System.Globalization;
using System.Windows.Controls;

namespace DimensionsHelper.Client.ValidationRules;

public class IntegerRangeValidationRule : ValidationRule
{
    public int UpperBoundary { get; set; }

    public int LowerBoundary { get; set; } = 1;

    public bool IsClosedBoundary { get; set; } = true;


    public override ValidationResult Validate(object? value, CultureInfo cultureInfo)
    {
        int? integerValue = value switch
        {
            string str when int.TryParse(str, out int intRes) => intRes,
            int intNum => intNum,
            _ => null
        };

        if (integerValue == null)
        {
            return new ValidationResult(false,
                $"值{value}无效，应为区间'{(IsClosedBoundary ? "[" : "(")}{LowerBoundary}..{UpperBoundary}{(IsClosedBoundary ? "]" : ")")}'内的整数。");
        }

        if ((IsClosedBoundary && integerValue >= LowerBoundary && integerValue <= UpperBoundary) ||
            (!IsClosedBoundary && integerValue > LowerBoundary && integerValue < UpperBoundary))
        {
            return ValidationResult.ValidResult;
        }

        return new ValidationResult(false,
            $"值{value}无效，应为区间'{(IsClosedBoundary ? "[" : "(")}{LowerBoundary}..{UpperBoundary}{(IsClosedBoundary ? "]" : ")")}'内的整数。");
    }
}